﻿using M_Ingredient.API.Application.Command.IngredientCommand;
using M_Ingredient.Domain;
using M_Ingredient.Domain.Dto;
using M_Ingredient.Repository.Interface;
using M_Quality.Domain;
using MediatR;

namespace M_Ingredient.API.Application.CommandHandler.IngredientCommandHandler
{
    public class IngredientShowCommandHandler : IRequestHandler<IngredientShowCommand, PageDto<Ingredient>>
    {
        protected readonly IIngredientRepository ingredientRepository;

        public IngredientShowCommandHandler(IIngredientRepository ingredientRepository)
        {
            this.ingredientRepository = ingredientRepository;
        }

        public async Task<PageDto<Ingredient>> Handle(IngredientShowCommand request, CancellationToken cancellationToken)
        {
            var res = await ingredientRepository.GetAsync(o => o.IsDeleted == false);

            if (!string.IsNullOrEmpty(request.Ingredientnumber))
            {
                res = res.Where(o => o.Ingredientnumber.Contains(request.Ingredientnumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.IngredientName))
            {
                res = res.Where(o => o.IngredientName.Contains(request.IngredientName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.State))
            {
                res = res.Where(o => o.State==request.State).ToList();
            }
            if (request.Pagesize == null)
            {
                request.Pagesize = res.Count();
            }
            if (request.Pageindex == null)
            {
                request.Pageindex = 1;
            }

            PageDto<Ingredient> page = new PageDto<Ingredient>();
            var size = request.Pagesize;
            var index = request.Pageindex;
            page.TotalCount = res.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)size);
            page.list = res.OrderByDescending(o => o.IngredientId).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return page;
        }
    }
}
